package com.wechat.service.storage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swak.annotation.FluxService;
import com.wechat.dto.ContactDTO;
import com.wechat.dto.ContactHeadimgDTO;
import com.wechat.login.Login;
import com.wechat.service.ContactHeadimgService;
import com.wechat.service.ContactService;
import com.wechat.service.SubjectService;

/**
 * SubjectServiceImpl.
 * 
 * @author DELL
 */
@FluxService
@Service("wechatSubjectServiceImpl")
public class SubjectServiceImpl extends SubjectStorageService implements SubjectService {

	@Autowired
	private SubjectHeadimgStorageService headimgStorageService;
	@Autowired
	private ContactHeadimgService contactHeadimgService;
	@Autowired
	private ContactService contactService;

	@Override
	@Transactional
	public ContactDTO me() {

		// 当前的用户
		Login login = this.getLogin();

		// 返回联系人信息
		return this.contact(login.getId());
	}

	@Override
	@Transactional
	public ContactDTO contact(String contactID) {

		// 对应的联系人
		ContactDTO contact = this.contactService.get(contactID);

		// 返回联系人信息
		return contact.setHeadimg(this.headimg(contactID));
	}

	@Override
	public ContactHeadimgDTO headimg(String contactID) {

		// 对应的头像
		ContactHeadimgDTO headimg = this.contactHeadimgService.get(contactID);

		// 设置实际的头像
		if (headimg != null) {
			headimg.setBigHeadimgFile(headimgStorageService.open(headimg.getBigHeadimg()));
			headimg.setSmallHeadimgFile(headimgStorageService.open(headimg.getSmallHeadimg()));
		}

		return headimg;
	}

	@Override
	@Transactional
	public void saveHeadimg(ContactDTO contact, byte[] image) {
		String imageUrl = this.headimgStorageService.save(image);
		this.contactHeadimgService
				.save(ContactHeadimgDTO.of().setId(contact.getId()).setBigHeadimg(imageUrl).setSmallHeadimg(imageUrl));
	}

	@Override
	@Transactional
	public void saveHeadimg(byte[] image) {
		this.saveHeadimg(ContactDTO.of().setId(this.getLogin().getId()), image);
	}

}
